package com.anytrek.websocket.java;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/ws1")
@Component
@Slf4j
public class MyWebSocketServerEndpoint {
    private static final Map<String, Session> sessionBeanMap;
    private static final StringBuffer stringBuffer;

    static {
        sessionBeanMap = new ConcurrentHashMap<>();
        stringBuffer = new StringBuffer();
    }

    // 连接建立时执行的操作
    @OnOpen
    public void onOpen(Session session) throws IOException {
        sessionBeanMap.put(session.getId(), session);
        stringBuffer.append(session.getId()).append("进入了群聊<br/>");
        log.debug("Client{} : 进入了群聊", session.getId());
        sendMessageToAll(stringBuffer.toString());
    }

    // 收到客户端消息时执行的操作
    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        stringBuffer.append(session.getId()).append(":").append(message).append("<br/>");
        log.debug("{} : {}", session.getId(), message);
        sendMessageToAll(stringBuffer.toString());
    }

    // 连接关闭时执行的操作
    @OnClose
    public void onClose(Session session) throws IOException {
        sessionBeanMap.remove(session.getId());
        log.debug("Client{} : 离开了群聊", session.getId());
        sendMessageToAll(session.getId() + " 离开了群聊");
    }

    // 向指定客户端发送消息
    private void sendMessage(Session session, String message) throws IOException {
        if (session.isOpen()) {
            session.getBasicRemote().sendText(message);
        }
    }

    // 向所有已连接的客户端发送消息
    private void sendMessageToAll(String message) throws IOException {
        for (Session session : sessionBeanMap.values()) {
            sendMessage(session, message);
        }
    }
}